#include "bsp_esp.h"
#include "usart.h"
#include "bsp_led.h"
#include "bsp_lcd.h"
#include "rtc.h"
#include "bsp_dec_font.h"

static const uint8_t *pu8AtCmd = "AT\r\n";
static const uint8_t *pu8CloseCallBack = "ATE0\r\n";
static const uint8_t *pu8sntpserver = "AT+CIPSNTPCFG=1,8,\"cn.ntp.org.cn\",\"ntp.sjtu.edu.cn\"\r\n";
static const uint8_t *pu8GetTimeCmd = "AT+CIPSNTPTIME?\r\n";

static uint8_t *pu8newshost = "dsp.lenovo.com.cn";
static uint8_t *pu8newsrequestpar = "https://dsp.lenovo.com.cn/lenovo/bid?positionId=50411";

static const uint8_t *pu8weatherhost = "api.seniverse.com";
static const uint8_t *pu8weatherquestpar = "/v3/weather/now.json?key=SnRC8TJ14reUFkaKf&location=Shanghai&language=zh-Hans&unit=c";

static uint8_t _judge_date_time(char *pu8Data);

void bsp_esp_init(void)
{
    bsp_led_on(5);
    HAL_UART_Transmit(&huart2, pu8CloseCallBack, strlen((char *)pu8CloseCallBack), 0xFF);
    HAL_Delay(10);
    HAL_UART_Transmit(&huart2, pu8AtCmd, strlen((char *)pu8AtCmd), 0xFF);
    HAL_Delay(10);
    bsp_led_off(5);
    if(NULL == strstr((char*)g_pau8Uart2RxBuf, "OK"))
    {
        bsp_led_on(2);
        printf("[ERROR] ESP8266 init failed!\n");
        LCD_ShowString(0,32,200,16,16,"ESP8266 init failed!",0xFFFF);
        return;
    }
    HAL_UART_Transmit(&huart2, pu8sntpserver, strlen((char *)pu8sntpserver), 0xFF);
    LCD_ShowString(0,32,200,16,16,"ESP8266 init success!",0xFFFF);
    return;
}

void bsp_esp_get_time(void)
{
    SyncState NowData = WeekDay;
    char *p8Data = NULL;
    char cTemp[5] = {0};
    uint8_t i = 0;
    HAL_UART_Transmit(&huart2, pu8GetTimeCmd, strlen((char *)pu8GetTimeCmd), 0xFF);
    HAL_Delay(10);
    p8Data = strstr((char *)g_pau8Uart2RxBuf, "+CIPSNTPTIME:");
    if(NULL == p8Data)
    {
        bsp_led_on(2);
        return;
    }
    p8Data += strlen("+CIPSNTPTIME:");

    while((*p8Data) != '\0')
    {
        if(     *p8Data == '\t' 
            ||  *p8Data == ':'
            ||  *p8Data == '\n'
			||	*p8Data == ' ')
        {
            switch(NowData)
            {
                case WeekDay:
                    g_rtcDate.WeekDay = _judge_date_time(cTemp);
                    i = 0;
                    NowData = Month;
                    break;
                case Month:
                    g_rtcDate.Month = _judge_date_time(cTemp);
                    i = 0;
                    NowData = Day;
                    break;
                case Day:
                    g_rtcDate.Date = atoi(cTemp);
                    i = 0;
                    NowData = Hour;
                    break;
                case Hour:
                    g_rtcTime.Hours = atoi(cTemp);
                    i = 0;
                    NowData = Minute;
                    break;
                case Minute:
                    g_rtcTime.Minutes = atoi(cTemp);
                    i = 0;
                    NowData = Second;
                    break;
                case Second:
                    if(IS_RTC_SECONDS(atoi(cTemp) + 13))
                    {
                        g_rtcTime.Seconds = atoi(cTemp) + 13;
                    }
                    else
                    {
                        g_rtcTime.Seconds = atoi(cTemp) + 13 - 60;
                        g_rtcTime.Minutes += 1;
                    }
                    i = 0;
                    NowData = Year;
                    break;
                case Year:
                    if(IS_RTC_YEAR(atoi(cTemp) - 2000))
                    {
                        g_rtcDate.Year = atoi(cTemp) - 2000;
                    }
                    else
                    {
                        g_rtcDate.Year = 24;
                    }
                    HAL_RTC_SetTime(&hrtc,&g_rtcTime, RTC_FORMAT_BIN);
                    HAL_RTC_SetDate(&hrtc,&g_rtcDate,RTC_FORMAT_BIN);
                    return;
            }
        }
        else
        {
            cTemp[i++] = *p8Data;
        }
        p8Data ++;
    }
}

void bsp_esp_get_weather(void)
{
    char acCmd[150] = {0};
    char acWeather[] = "今日天气：";
    char acTemp[] = "温度：";
    char acsign[] = "℃";
    char *pcWeatherBegin = NULL;
    char *pcWeatherEnd = NULL;
    uint8_t i = 0;
    uint8_t u8ArrLen = 0;

    sprintf(acCmd, "AT+CIPSTART=\"TCP\",\"%s\",80\r\n",pu8weatherhost);
    HAL_UART_Transmit(&huart2, (uint8_t *)acCmd, strlen(acCmd), 0xFF);
    HAL_Delay(200);
    if(NULL == strstr((char *)g_pau8Uart2RxBuf,"CONNECT"))
    {
        return;
    }
    HAL_UART_Transmit(&huart2, (uint8_t *)"AT+CIPMODE=1\r\n", strlen((char *)"AT+CIPMODE=1\r\n"), 0xFF);
    HAL_Delay(5);
    if(NULL == strstr((char *)g_pau8Uart2RxBuf,"OK"))
    {
        return;
    }
    HAL_UART_Transmit(&huart2, (uint8_t *)"AT+CIPSEND\r\n", strlen((char *)"AT+CIPSEND\r\n"), 0xFF);
    HAL_Delay(50);
    if(NULL == strstr((char *)g_pau8Uart2RxBuf,">"))
    {
        return;
    }
    sprintf(acCmd, "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", pu8weatherquestpar,pu8weatherhost);
    HAL_UART_Transmit(&huart2, (uint8_t *)acCmd, strlen(acCmd), 0xFF);
	HAL_Delay(500);

    //此时SRAM应该存有数据
    u8ArrLen = strlen(acCmd);
    memset(acCmd, 0, u8ArrLen);
    pcWeatherBegin = strstr((char *)g_pau8Uart2RxBuf,"text");  //获取中文开始位置
    pcWeatherEnd   = strstr((char *)g_pau8Uart2RxBuf,"\",\"code\"");   //获取中文结束位置
    if(pcWeatherBegin == NULL || pcWeatherEnd == NULL)
    {
        goto end;
    }
    pcWeatherBegin += 7;
    while(pcWeatherBegin != pcWeatherEnd)
    {
        acCmd[i] = *pcWeatherBegin;
        i++;
        pcWeatherBegin++;
    }
    u8ArrLen = strlen(acCmd);
    bsp_switch_utf8_to_gb2312((uint8_t *)acWeather,strlen(acWeather)); //刷"今日天气:"
    bsp_lcd_showChineseStr(0,0,0xFFFF,0x0000);
    bsp_switch_utf8_to_gb2312((uint8_t *)acTemp,strlen(acTemp));       //刷"温度:"
    bsp_lcd_showChineseStr(0,140,0xFFFF,0x0000);
	bsp_switch_utf8_to_gb2312((uint8_t *)acsign,strlen(acsign));       //刷"℃"
    bsp_lcd_showChineseStr(0,210,0xFFFF,0x0000);  


    bsp_switch_utf8_to_gb2312((uint8_t *)acCmd,u8ArrLen);      //刷天气
	bsp_lcd_showChineseStr(0,80,0xFFFF,0x0000);

    pcWeatherBegin = strstr((char *)g_pau8Uart2RxBuf,"temperature");
    if(pcWeatherBegin == NULL)
    {
        goto end;
    }
    pcWeatherBegin += 14;
    memset(acCmd, 0, u8ArrLen);
    i = 0;
    while(*pcWeatherBegin != '\"')
    {
        acCmd[i] = *pcWeatherBegin;
        i++;
        pcWeatherBegin++;
    }
    LCD_ShowString(190,0,16,16,16,(uint8_t *)acCmd,0xFFFF);

    end:
    HAL_Delay(200);
    HAL_UART_Transmit(&huart2, (uint8_t *)"+++", strlen((char *)"+++"), 0xFF);
    HAL_Delay(200);
    HAL_UART_Transmit(&huart2, (uint8_t *)"AT+CIPCLOSE\r\n", strlen((char *)"AT+CIPCLOSE\r\n"), 0xFF);
}


void bsp_esp_get_news(void)
{
    char acNewsTitle[] = "今日头条：";
    char acStr[200] = {0};
    char *pcNewsBegin = (char *)g_pau8Uart2RxBuf;
    uint8_t i = 0;
    uint8_t j = 0;
    uint8_t u8ArrLen = 0;
    const char *pcKeyWord = "\"title\":\"";
    bsp_switch_utf8_to_gb2312((uint8_t *)acNewsTitle,strlen(acNewsTitle));       //刷"今日头条:"
    bsp_lcd_showChineseStr(32,0,0xFFFF,0x0000);

    sprintf(acStr, "AT+CIPSTART=\"TCP\",\"%s\",80\r\n",pu8newshost);
    HAL_UART_Transmit(&huart2, (uint8_t *)acStr, strlen(acStr), 0xFF);
    HAL_Delay(200);
    if(NULL == strstr((char *)g_pau8Uart2RxBuf,"CONNECT"))
    {
        return;
    }
    HAL_UART_Transmit(&huart2, (uint8_t *)"AT+CIPMODE=1\r\n", strlen((char *)"AT+CIPMODE=1\r\n"), 0xFF);
    HAL_Delay(5);
    if(NULL == strstr((char *)g_pau8Uart2RxBuf,"OK"))
    {
        return;
    }
    HAL_UART_Transmit(&huart2, (uint8_t *)"AT+CIPSEND\r\n", strlen((char *)"AT+CIPSEND\r\n"), 0xFF);
    HAL_Delay(50);
    if(NULL == strstr((char *)g_pau8Uart2RxBuf,">"))
    {
        return;
    }
    sprintf(acStr, "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", pu8newsrequestpar,pu8newshost);
    HAL_UART_Transmit(&huart2, (uint8_t *)acStr, strlen(acStr), 0xFF);
	HAL_Delay(500);

    for(i=0; i < 10; i++)
    {
        //先刷序号
        j = 0;
        u8ArrLen = strlen(acStr);
        memset(acStr, 0, u8ArrLen);
        sprintf(acStr, "%d. ",i+1);
        LCD_ShowString(0,48+i*16,24,16,16,(uint8_t *)acStr,0xFFFF);
        //再刷新闻
        pcNewsBegin = strstr(pcNewsBegin,pcKeyWord);
        if(NULL == pcNewsBegin)
        {
            goto end;
        }
        pcNewsBegin += strlen(pcKeyWord);
        while(*pcNewsBegin != '\"')
        {
            acStr[j] = *pcNewsBegin;
            pcNewsBegin++;
            j++;
        }
        bsp_switch_utf8_to_gb2312((uint8_t *)acStr,strlen(acStr));
        bsp_lcd_showChineseStr(48+i*16,24,0xFFFF,0x0000);
    }

    end:
    HAL_Delay(200);
    HAL_UART_Transmit(&huart2, (uint8_t *)"+++", strlen((char *)"+++"), 0xFF);
    HAL_Delay(200);
    HAL_UART_Transmit(&huart2, (uint8_t *)"AT+CIPCLOSE\r\n", strlen((char *)"AT+CIPCLOSE\r\n"), 0xFF);
}



static uint8_t _judge_date_time(char *pu8Data)
{
    if(pu8Data == NULL)
    {
        return 0xFF;
    }

    switch(*pu8Data)
    {
        case 'A':
        if(NULL != strstr(pu8Data,"Apr"))return RTC_MONTH_APRIL;
        if(NULL != strstr(pu8Data,"Aug"))return RTC_MONTH_AUGUST;
        case 'D':
        return RTC_MONTH_DECEMBER;
        case 'F':
        if(NULL != strstr(pu8Data,"Feb"))return RTC_MONTH_FEBRUARY;
        if(NULL != strstr(pu8Data,"Fri"))return RTC_WEEKDAY_FRIDAY;
        case 'J':
        if(NULL != strstr(pu8Data,"Jan"))return RTC_MONTH_JANUARY;
        if(NULL != strstr(pu8Data,"Jul"))return RTC_MONTH_JULY;
        if(NULL != strstr(pu8Data,"Jun"))return RTC_MONTH_JUNE;
        case 'M':
        if(NULL != strstr(pu8Data,"Mar"))return RTC_MONTH_MARCH;
        if(NULL != strstr(pu8Data,"May"))return RTC_MONTH_MAY;
        if(NULL != strstr(pu8Data,"Mon"))return RTC_WEEKDAY_MONDAY;
        case 'N':
        return RTC_MONTH_NOVEMBER;
        case 'O':
        return RTC_MONTH_OCTOBER;
        case 'S':
        if(NULL != strstr(pu8Data,"Sep"))return RTC_MONTH_SEPTEMBER;
        if(NULL != strstr(pu8Data,"Sat"))return RTC_WEEKDAY_SATURDAY;
        if(NULL != strstr(pu8Data,"Sun"))return RTC_WEEKDAY_SUNDAY;
        case 'T':
        if(NULL != strstr(pu8Data,"Tue"))return RTC_WEEKDAY_TUESDAY;
        if(NULL != strstr(pu8Data,"Thu"))return RTC_WEEKDAY_THURSDAY;
        case 'W':
        return RTC_WEEKDAY_WEDNESDAY;
    }

	return 0xFF;
}




